package com.huawei.deveco.exportprofiler;

import com.huawei.deveco.insight.ohos.common.ProjectContext;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.jcef.JBCefBrowser;
import org.cef.browser.CefMessageRouter;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class ExportAction extends AnAction {
    private static final Map<String, CefMessageRouter> routerMaps = new HashMap<>();

    public static void removeRouterByUUID(String uuid) {
        if (!routerMaps.containsKey(uuid)) {
            return;
        }
        var jbBrowser = ProjectContext.getJbCefBrowser();
        if (jbBrowser == null) {
            return;
        }
        var router = routerMaps.get(uuid);
        router.dispose();
        jbBrowser.getJBCefClient().getCefClient().removeMessageRouter(router);
        routerMaps.remove(uuid);
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        var isProfilerOpened = isProfilerOpened(e.getProject());
        if (!isProfilerOpened) {
            e.getPresentation().setEnabledAndVisible(false);
            return;
        }
        var jbBrowser = ProjectContext.getJbCefBrowser();
        if (jbBrowser == null) {
            e.getPresentation().setEnabledAndVisible(false);
            return;
        }
        e.getPresentation().setEnabledAndVisible(true);
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
        var jbBrowser = ProjectContext.getJbCefBrowser();
        // 给调优注册一个 Router 来进行数据截取，在方法调用完成后清理该 Router
        CefMessageRouter router = CefMessageRouter.create();
        router.addHandler(new MsgRouterHandlerAdapter(), false);
        jbBrowser.getJBCefClient().getCefClient().addMessageRouter(router);
        var uuid = UUID.randomUUID().toString();
        executeTask(uuid, jbBrowser);
        routerMaps.put(uuid, router);
    }

    private boolean isProfilerOpened(Project project) {
        if (project == null) {
            return false;
        }
        var tw = ToolWindowManager.getInstance(project).getToolWindow("Profiler");
        if (tw == null) {
            return false;
        }
        return tw.isAvailable() && tw.isVisible();
    }

    private void executeTask(String uuid, JBCefBrowser browser) {
        String command = String.format("""
                (function() {
                    // 获取当前选中的数据的 session 信息
                    const el = document.querySelector('[data-testid="arkuiDetails"]')
                    if (!el) {
                        alert('No data')
                        return
                    }
                    const parentEl = el.parentElement
                    const fiberName = Object.getOwnPropertyNames(parentEl).find((key) => key.startsWith('__reactFiber$'))
                    const children = parentEl[`${fiberName}`].pendingProps.children
                    const data = {
                        uuid: '%s',
                        columns: []
                    }
                    if (children) {
                        data.columns = [...children.props.data]
                    }
                    window.cefQuery({
                        request: JSON.stringify({
                            key: 'exportFilterDetail',
                            data
                        })
                    })
                }) ()
                """, uuid);
        browser.getCefBrowser().executeJavaScript(command, browser.getCefBrowser().getURL(), 0);
    }
}
